package com.xinyue.cross.server.server.handler;

import com.xinyue.cross.server.server.IHandlerMessageListener;
import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import com.xinyue.game.utils.GameServerUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyLogicMessageHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(NettyLogicMessageHandler.class);
    private IHandlerMessageListener handlerMessageListener;

    public NettyLogicMessageHandler(IHandlerMessageListener handlerMessageListener) {
        this.handlerMessageListener = handlerMessageListener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接创建成功，channelId: {}", GameServerUtil.getChannelId(ctx.channel()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            GameServerMessageModel<GameServerRequestHeader> gameServerMessageModel = (GameServerMessageModel) msg;
            handlerMessageListener.handlerMessage(gameServerMessageModel, ctx);
        } catch (Throwable e) {
            logger.error("服务消息处理异常", e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("服务器异常", cause);
    }
}
